# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 流程状态
"""
from fastapi import APIRouter, Request, Body, Query

from config import Config
from project.core.exception import NoRecordError, BizError
from project.core.function import json_response
from project.lib.decorator import api_common, exec_duration
from project.lib.constant import DEFAULT_VALUE
from project.model.database.flow import FlowProcess
from project.service.flow import FlowService


process_router = APIRouter(prefix='/m', tags=['manager.process'])


@process_router.post('/flow/process/add', summary='新增流程状态')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_process_add(request: Request,
                              name: str = Body(..., title='状态名称'),
                              flow_id: int = Body(..., title='服务流程id'),
                              remark: str = Body('', title='备注信息'),
                              is_display: int = Body(0, title='是否显示'),
                              digital_human_broadcast: str = Body('', max_length=30, title='数字人播报内容'),
                              session=None,
                              body_params=None):
    """
    **desc**: 新增流程状态

    **url**: http(s)://{0}.udicaria.com/m/flow/process/add

    **method**: POST

        <body>:
            name: 状态名称
            flow_id: 服务流程id
            remark: 备注信息
            is_display: 是否显示(0:否, 1:是)
            digital_human_broadcast: 数字人播报内容

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: None
            exec_time: 接口后端处理时长
        }
    """
    process = await FlowService.do_process_add(session, body_params)

    return json_response(data=process.dict('id'))


@process_router.post('/flow/process/update', summary='修改流程状态')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_process_update(request: Request,
                                 id: int = Body(..., title='流程状态id'),
                                 name: str = Body(DEFAULT_VALUE, title='流程名称'),
                                 remark: str = Body(DEFAULT_VALUE, title='备注信息'),
                                 is_display: int = Body(DEFAULT_VALUE, title='是否显示'),
                                 digital_human_broadcast: str = Body(DEFAULT_VALUE, max_length=30, title='数字人播报内容'),
                                 session=None,
                                 body_params=None):
    """
    **desc**: 修改服务流程状态

    **url**: http(s)://{0}.udicaria.com/m/flow/process/update

    **method**: POST

        <body>:
            id: 流程状态id
            name: 流程名称
            remark: 备注信息
            is_display: 是否显示(0:否, 1:是)
            digital_human_broadcast: 数字人播报内容

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: None
            exec_time: 接口后端处理时长
        }
    """
    await FlowService.do_process_update(session, body_params)

    return json_response()


@process_router.get('/flow/process/detail', summary='流程状态详情')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def get_flow_process_detail(request: Request,
                                  id: int = Query(..., title='流程状态id'),
                                  session=None):
    """
    **desc**: 流程状态详情

    **url**: http(s)://{0}.udicaria.com/m/flow/process/detail

    **method**: GET

        <body>:
            id: 流程状态id

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                name: 流程状态名称
                flow_id: 所属服务流程id
                flow_code: 所属服务流程编号
                rank: 流程排序
                remark: 备注信息
                is_display: 是否显示(0:否, 1:是)
            }
            exec_time: 接口后端处理时长
        }
    """
    flow_process = await FlowProcess.fetch_one(session, wheres=(FlowProcess.id==id))

    return json_response(data=flow_process.dict() if flow_process else {})


@process_router.get('/flow/process/list', summary='流程状态列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def get_flow_process_list(request: Request,
                                flow_id: int = Query(..., title='服务流程id'),
                                is_display: int = Query(0, title='仅查看显示的状态(0:否, 1:是)'),
                                session=None):
    """
    **desc**: 服务流程状态列表

    **url**: http(s)://{0}.udicaria.com/m/flow/process/list

    **method**: GET

        <body>:
            flow_id: 服务流程id
            is_display: 仅查看显示的状态(0:否, 1:是)

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    name: 流程状态名称
                    flow_id: 所属服务流程id
                    flow_code: 所属服务流程编号
                    rank: 流程排序
                    remark: 备注信息
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    if is_display:
        data = await FlowProcess.fetch_all(session, wheres=(FlowProcess.flow_id == flow_id, FlowProcess.is_display, ~FlowProcess.is_deleted), orders=(FlowProcess.rank, ))
    else:
        data = await FlowProcess.fetch_all(session, wheres=(FlowProcess.flow_id == flow_id, ~FlowProcess.is_deleted), orders=(FlowProcess.rank, ))

    return json_response(data=[v.dict() for v in data])


@process_router.post('/flow/process/delete', summary='删除流程状态')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_process_delete(request: Request, id: int = Body(..., title='流程状态id', embed=True), session=None):
    """
    **desc**: 删除流程状态

    **url**: http(s)://{0}.udicaria.com/m/flow/process/delete

    **method**: GET

    **params**:

        <body>:
            id: 角色id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    await FlowService.do_process_delete(session, flow_process_id=id)

    return json_response()


@process_router.post('/flow/process/order', summary='流程状态排序')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def do_flow_process_order(request: Request,
                                ids: list[int] = Body(..., title='流程状态id', embed=True),
                                session=None):
    """
    **desc**: 流程状态排序

    **url**: http(s)://{0}.udicaria.com/m/flow/process/order

    **method**: GET

    **params**:

        <body>:
            ids: 流程状态id列表

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    for idx, flow_process_id in enumerate(ids):
        # no_record_error=False 如果碰到检索不到的情况，不会创建新记录
        await FlowProcess.create_modify(session, wheres=(FlowProcess.id == flow_process_id), rank=idx, no_to_create=False)

    return json_response()
